<template>
  <div class="table-box">
    <ProTable
      ref="proTable"
      title="替代料管理"
      :columns="columns"
      :request-api="getSubstituteMaterialList"
      :init-param="initParam"
      :data-callback="dataCallback"
    >
      <!-- 表格 header 按钮 -->
      <template #tableHeader="scope">
        <el-button type="primary" :icon="CirclePlus" @click="handleAdd">新增替代料</el-button>
        <el-button :icon="Download" @click="handleExport">导出</el-button>
      </template>

      <!-- 状态 -->
      <template #status="scope">
        <el-tag :type="getStatusType(scope.row.status)">
          {{ getStatusText(scope.row.status) }}
        </el-tag>
      </template>

      <!-- 替代比例 -->
      <template #substituteRatio="scope">
        <span>{{ scope.row.substituteRatio }}%</span>
      </template>

      <!-- 有效期 -->
      <template #validPeriod="scope">
        <div>
          <div v-if="scope.row.validFrom">开始: {{ formatDateTime(scope.row.validFrom) }}</div>
          <div v-if="scope.row.validTo">结束: {{ formatDateTime(scope.row.validTo) }}</div>
          <span v-if="!scope.row.validFrom && !scope.row.validTo">-</span>
        </div>
      </template>

      <!-- 创建时间 -->
      <template #createdTime="scope">
        <span>{{ formatDateTime(scope.row.createdTime) }}</span>
      </template>

      <!-- 操作 -->
      <template #operation="scope">
        <el-button type="primary" link :icon="View" @click="handleView(scope.row)">查看</el-button>
        <el-button 
          v-if="scope.row.status === 'DRAFT'" 
          type="primary" 
          link 
          :icon="EditPen" 
          @click="handleEdit(scope.row)"
        >
          编辑
        </el-button>
        <el-dropdown @command="(command: string) => handleDropdownCommand(command, scope.row)">
          <el-button type="primary" link>
            更多<el-icon class="el-icon--right"><arrow-down /></el-icon>
          </el-button>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item 
                v-if="scope.row.status === 'PENDING_APPROVAL'" 
                command="approve"
              >
                审核通过
              </el-dropdown-item>
              <el-dropdown-item 
                v-if="scope.row.status === 'PENDING_APPROVAL'" 
                command="reject"
              >
                审核拒绝
              </el-dropdown-item>
              <el-dropdown-item 
                v-if="scope.row.status === 'ACTIVE'" 
                command="applyToWorkOrder"
              >
                应用到工单
              </el-dropdown-item>
              <el-dropdown-item 
                v-if="['DRAFT', 'REJECTED'].includes(scope.row.status)" 
                command="delete"
              >
                删除
              </el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </template>
    </ProTable>

    <!-- 表单抽屉 -->
    <SubstituteMaterialDrawer ref="drawerRef" />
    
    <!-- 详情抽屉 -->
    <SubstituteMaterialDetail ref="detailRef" />
  </div>
</template>

<script setup lang="ts" name="substituteMaterial">
import { ref, reactive } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { CirclePlus, EditPen, View, Download, ArrowDown } from "@element-plus/icons-vue";
import { ColumnProps } from "@/components/ProTable/interface";
import ProTable from "@/components/ProTable/index.vue";
import SubstituteMaterialDrawer from "./form.vue";
import SubstituteMaterialDetail from "./detail.vue";
import { substituteMaterialApi, type SubstituteMaterial } from "@/api/modules/substituteMaterial";

// ProTable 实例
const proTable = ref();

// 格式化时间
const formatDateTime = (dateTime: string) => {
  if (!dateTime) return "-";
  return new Date(dateTime).toLocaleString("zh-CN");
};

// 获取状态类型
const getStatusType = (status: string) => {
  const statusMap: Record<string, string> = {
    DRAFT: "info",
    PENDING_APPROVAL: "warning", 
    ACTIVE: "success",
    REJECTED: "danger",
    EXPIRED: "info",
    OBSOLETED: "info"
  };
  return statusMap[status] || "info";
};

// 获取状态文本
const getStatusText = (status: string) => {
  const statusMap: Record<string, string> = {
    DRAFT: "草稿",
    PENDING_APPROVAL: "待审批",
    ACTIVE: "可用", 
    REJECTED: "拒绝",
    EXPIRED: "已过期",
    OBSOLETED: "废止"
  };
  return statusMap[status] || status;
};

// 状态选项
const statusOptions = [
  { label: "草稿", value: "DRAFT" },
  { label: "待审批", value: "PENDING_APPROVAL" },
  { label: "可用", value: "ACTIVE" },
  { label: "拒绝", value: "REJECTED" },
  { label: "已过期", value: "EXPIRED" },
  { label: "废止", value: "OBSOLETED" }
];

// 表格配置项
const columns: ColumnProps[] = [
  { type: "selection", fixed: "left", width: 50 },
  { type: "index", label: "#", width: 80 },
  {
    prop: "mainMaterialCode",
    label: "主料编码",
    width: 150,
    search: { el: "input", props: { placeholder: "请输入主料编码" } }
  },
  {
    prop: "mainMaterialName", 
    label: "主料名称",
    width: 150
  },
  {
    prop: "substituteMaterialCode",
    label: "替代料编码", 
    width: 150,
    search: { el: "input", props: { placeholder: "请输入替代料编码" } }
  },
  {
    prop: "substituteMaterialName",
    label: "替代料名称",
    width: 150
  },
  {
    prop: "substituteRatio",
    label: "替代比例",
    width: 100
  },
  {
    prop: "priority",
    label: "优先级",
    width: 80
  },
  {
    prop: "status",
    label: "状态",
    width: 100,
    search: {
      el: "select",
      props: { placeholder: "请选择状态" }
    },
    enum: statusOptions
  },
  {
    prop: "validPeriod",
    label: "有效期",
    width: 180
  },
  {
    prop: "createdTime",
    label: "创建时间",
    width: 160
  },
  {
    prop: "operation",
    label: "操作",
    width: 200,
    fixed: "right"
  }
];

// 初始化参数
const initParam = reactive({});

// 数据回调处理
const dataCallback = (data: any) => {
  return {
    list: data.records || [],
    total: Number(data.total) || 0
  };
};

// 获取替代料列表
const getSubstituteMaterialList = (params: any) => {
  return substituteMaterialApi.getList(params);
};

// 表单抽屉引用
const drawerRef = ref<InstanceType<typeof SubstituteMaterialDrawer>>();
const detailRef = ref<InstanceType<typeof SubstituteMaterialDetail>>();

// 获取表格数据列表
const getTableList = () => {
  proTable.value?.getTableList();
};

// 新增
const handleAdd = () => {
  const params = {
    title: "新增替代料",
    isView: false,
    row: {},
    api: addSubstituteMaterial,
    getTableList
  };
  drawerRef.value?.acceptParams(params);
};

// 编辑
const handleEdit = (row: SubstituteMaterial.ViewEntity) => {
  const params = {
    title: "编辑替代料",
    isView: false,
    row: { ...row },
    api: editSubstituteMaterial,
    getTableList
  };
  drawerRef.value?.acceptParams(params);
};

// 查看
const handleView = (row: SubstituteMaterial.ViewEntity) => {
  const params = {
    title: "替代料详情",
    row: { ...row }
  };
  detailRef.value?.acceptParams(params);
};

// 新增替代料
const addSubstituteMaterial = async (params: SubstituteMaterial.AddRequest) => {
  return await substituteMaterialApi.add(params);
};

// 编辑替代料
const editSubstituteMaterial = async (params: SubstituteMaterial.ViewEntity) => {
  return await substituteMaterialApi.update(params.id, {
    substituteRatio: params.substituteRatio,
    priority: params.priority,
    validFrom: params.validFrom,
    validTo: params.validTo
  });
};

// 下拉菜单命令处理
const handleDropdownCommand = async (command: string, row: SubstituteMaterial.ViewEntity) => {
  switch (command) {
    case "approve":
      await handleApprove(row);
      break;
    case "reject":
      await handleReject(row);
      break;
    case "applyToWorkOrder":
      await handleApplyToWorkOrder(row);
      break;
    case "delete":
      await handleDelete(row);
      break;
  }
};

// 审核通过
const handleApprove = async (row: SubstituteMaterial.ViewEntity) => {
  try {
    await ElMessageBox.confirm(`确认审核通过替代料 "${row.substituteMaterialName}" 吗？`, "审核确认", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning"
    });

    await substituteMaterialApi.approve(row.id);
    ElMessage.success("审核通过成功");
    getTableList();
  } catch (error) {
    if (error !== "cancel") {
      ElMessage.error("审核通过失败");
    }
  }
};

// 审核拒绝
const handleReject = async (row: SubstituteMaterial.ViewEntity) => {
  try {
    const { value: reason } = await ElMessageBox.prompt("请输入拒绝原因", "审核拒绝", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      inputType: "textarea",
      inputValidator: (value: string) => {
        if (!value || value.trim() === "") {
          return "拒绝原因不能为空";
        }
        return true;
      }
    });

    await substituteMaterialApi.reject(row.id, { rejectReason: reason });
    ElMessage.success("审核拒绝成功");
    getTableList();
  } catch (error) {
    if (error !== "cancel") {
      ElMessage.error("审核拒绝失败");
    }
  }
};

// 应用到工单
const handleApplyToWorkOrder = async (row: SubstituteMaterial.ViewEntity) => {
  try {
    const { value: workOrderId } = await ElMessageBox.prompt("请输入工单ID", "应用到工单", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      inputPattern: /^\d+$/,
      inputErrorMessage: "请输入有效的工单ID"
    });

    const { value: actualQuantity } = await ElMessageBox.prompt("请输入实际使用数量", "应用到工单", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      inputPattern: /^\d+(\.\d+)?$/,
      inputErrorMessage: "请输入有效的数量"
    });

    await substituteMaterialApi.applyToWorkOrder(row.id, { 
      workOrderId: Number(workOrderId), 
      actualQuantity: Number(actualQuantity) 
    });
    ElMessage.success("应用到工单成功");
    getTableList();
  } catch (error) {
    if (error !== "cancel") {
      ElMessage.error("应用到工单失败");
    }
  }
};

// 删除
const handleDelete = async (row: SubstituteMaterial.ViewEntity) => {
  try {
    await ElMessageBox.confirm(`确认删除替代料关系吗？`, "删除确认", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning"
    });

    await substituteMaterialApi.remove(row.id);
    ElMessage.success("删除成功");
    getTableList();
  } catch (error) {
    if (error !== "cancel") {
      ElMessage.error("删除失败");
    }
  }
};

// 导出数据
const handleExport = async () => {
  try {
    ElMessage.info("正在导出数据...");
    // 这里可以调用导出API
    ElMessage.success("导出成功");
  } catch (error) {
    ElMessage.error("导出失败");
  }
};
</script>

<style scoped>
.search-form {
  background-color: #fff;
  padding: 20px;
  border-radius: 4px;
  margin-bottom: 16px;
}

.table-header {
  margin-bottom: 16px;
  display: flex;
  gap: 10px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
  flex-shrink: 0;
}
</style>